package com.leetcode.contest;

import java.math.BigDecimal;

/**
 * 5259. 计算应缴税款总额
 */
public class CalculateTax {
    static class Solution {
        public double calculateTax(int[][] brackets, int income) {
            if (income == 0) {
                return 0;
            }
            if (income <= brackets[0][0]) {
                BigDecimal multiply = BigDecimal.valueOf(income).multiply(BigDecimal.valueOf(brackets[0][1]).divide(BigDecimal.valueOf(100)).setScale(2));
                return multiply.doubleValue();
            }
            BigDecimal m = BigDecimal.valueOf(brackets[0][0]).multiply(BigDecimal.valueOf(brackets[0][1]).divide(BigDecimal.valueOf(100)).setScale(2));
            int reduce = income - brackets[0][0];
            int sum = brackets[0][0];

            for (int i = 1; i < brackets.length; i++) {
                int upper = brackets[i - 1][0];
                int percent = brackets[i][1];

                if (reduce > upper) {
                    reduce -= upper;
                    sum += reduce;
                    BigDecimal multiply = BigDecimal.valueOf((reduce)).multiply(BigDecimal.valueOf(percent).divide(BigDecimal.valueOf(100)).setScale(2));
                    m = m.add(multiply);
                } else {
                    if (sum < income) {
                        income -= sum;
                        BigDecimal multiply = BigDecimal.valueOf((income)).multiply(BigDecimal.valueOf(percent).divide(BigDecimal.valueOf(100)).setScale(2));
                        m = m.add(multiply);
                    }

                    break;
                }
            }

            return m.doubleValue();
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();

        int[][] brackets = {{10, 10}};
        int income = 5;

        solution.calculateTax(brackets, income);
    }
}
